package com.shu.mmall.service.impl;

import com.shu.mmall.common.Const;
import com.shu.mmall.common.Result;
import com.shu.mmall.common.TokenCache;
import com.shu.mmall.dao.UserMapper;
import com.shu.mmall.pojo.User;
import com.shu.mmall.service.IUserService;
import com.shu.mmall.util.EmptyUtil;
import com.shu.mmall.util.Md5Util;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author shujinhao
 */
@Service("userService")
public class UserServiceImpl implements IUserService {
    @Autowired
    UserMapper userMapper;


    @Override
    public Result<User> login(String username, String password) {
        int resultCount = userMapper.checkUsername(username);
        if (resultCount==0){
            return Result.createByErrorMessage("用户名不存在");
        }
        //密码登录md5
        User user = userMapper.selectLogin(username, Md5Util.md5EncodeUtf8(password));
        if (EmptyUtil.isNull(user)){
            return Result.createByErrorMessage("密码错误");
        }
        //密码置空
        user.setPassword(StringUtils.EMPTY);
        return Result.createBySuccess("登录成功",user);
    }

    @Override
    public Result<String> register(User user){
        Result<String> checkValid = this.checkValid(user.getUsername(), Const.USERNAME);
        if (!checkValid.isSuccess()){
            return checkValid;
        }
        checkValid = this.checkValid(user.getEmail(), Const.EMAIL);
        if (!checkValid.isSuccess()){
            return checkValid;
        }
        user.setRole(Const.Role.ROLE_CUSTOMER);
        //md5加密
        user.setPassword(Md5Util.md5EncodeUtf8(user.getPassword()));
        //插入数据库
        int resultCount = userMapper.insert(user);
        if (resultCount==0){
            return Result.createByErrorMessage("注册失败");
        }
        return  Result.createBySuccess("注册成功");
    }

    @Override
    public Result<String> checkValid(String str, String type){
        if (EmptyUtil.isEmpty(type)){
            return Result.createByErrorMessage("参数错误");
        }
        //开始校验
        if (Const.USERNAME.equals(type)){
            int resultCount = userMapper.checkUsername(str);
            if (resultCount>0){
                return Result.createByErrorMessage("用户名已存在");
            }
        }
        if (Const.EMAIL.equals(type)){
            int resultCount=userMapper.checkEmail(str);
            if (resultCount>0){
                return Result.createByErrorMessage("邮箱已存在");
            }
        }
        return Result.createBySuccessMessage("校验通过");
    }


    @Override
    public Result selectQuestion(String username){
        Result<String> checkValid = this.checkValid(username, Const.USERNAME);
        if (checkValid.isSuccess()){
            return Result.createByErrorMessage("用户不存在");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if (EmptyUtil.isEmpty(question)){
            return Result.createByErrorMessage("查询问题为空");
        }
        return Result.createBySuccess(question);
    }


    @Override
    public Result<String> checkAnswer(String username, String question, String answer){
        int resultCount=userMapper.checkAnswer(username,question,answer);
        if (resultCount>0){
            //说明问题以及答案是正确的
            String forgetToken=UUID.randomUUID().toString();
            //缓存
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);

            return Result.createBySuccess(forgetToken);
        }
        return Result.createByErrorMessage("问题答案错误");
    }

    @Override
    public Result<String> forgetRestPassword(String username, String passwordNew, String forgetToken){
        if (EmptyUtil.isEmpty(forgetToken)){
            return Result.createByErrorMessage("参数错误，token需要传递");
        }
        Result<String> checkValid = this.checkValid(username, Const.USERNAME);
        if (checkValid.isSuccess()){
            return Result.createByErrorMessage("用户不存在");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username);
        if (EmptyUtil.isEmpty(token)){
            return Result.createByErrorMessage("token过期");
        }
        if (EmptyUtil.equals(forgetToken,token)){
            String md5Password=Md5Util.md5EncodeUtf8(passwordNew);
            int rowCount = userMapper.updatePasswordByUsername(username, md5Password);
            if (rowCount>0){
                return Result.createBySuccessMessage("修改密码成功");
            }
        }else {
            return Result.createByErrorMessage("token错误，请重新获取重置密码的token");
        }

        return Result.createByErrorMessage("修改密码失败");
    }

    @Override
    public Result<String> resetPassword(String passwordOld, String passwordNew, User user){
        //防止横向越权，要校验一下这个用户的旧密码，一定要指定时这个用户
        int count = userMapper.checkPassword(Md5Util.md5EncodeUtf8(passwordOld), user.getId());
        if (count==0){
            return Result.createByErrorMessage("旧密码错误");
        }
        user.setPassword(Md5Util.md5EncodeUtf8(passwordNew));
        int rowCount = userMapper.updateByPrimaryKeySelective(user);
        if (rowCount>0){
            return Result.createBySuccessMessage("修改密码成功");
        }
        return Result.createByErrorMessage("修改密码失败");
    }

    @Override
    public Result<User> updateUserInfo(User user){
        //username不能被更新
        //email也要进行校验
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
        if (resultCount>0){
            return Result.createByErrorMessage("email已经存在，请更换email在尝试更新");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());
        //更新
        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if (updateCount>0){
            return Result.createBySuccess("更新个人信息成功",updateUser);
        }
        return Result.createByErrorMessage("更新个人信息失败");
    }

    @Override
    public Result<User> getInformation(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if (EmptyUtil.isNull(user)){
            return Result.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(EmptyUtil.EMPTY);
        return Result.createBySuccess(user);
    }
    //backend

    @Override
    public Result checkAdminRole(User user){
        if (EmptyUtil.isNotNull(user) && user.getRole() == Const.Role.ROLE_ADMIN){
            return Result.createBySuccess();
        }
        return Result.createByError();
    }

}
